<template>
  <div class="contractTemplate-page">
    <a-card :bordered="false">
      <!-- 表格顶部搜索部分 -->
      <c-table-search-form
        v-model="tableSearchForm"
        :datas="tableSearchFormData"
        @onAdd="handleAdd('', 'add')"
      ></c-table-search-form>

      <!-- 表格部分 -->
      <c-table
        :columns="tableColumns"
        :datas="tableData"
        :loading="loading"
        showPagination
        :paginationDatas="paginationDatas"
        @onPageSizeChange="onPageSizeChange"
        @onShowNumChange="onShowNumChange"
      >
        <!-- 表格自定义部分 -->
        <!-- 模板类型 -->
        <template slot="templateLimit" slot-scope="row">
           <a-tag
            :color="$dealDic(contractTemplateType,row.tableRow,'tagColor')"
          >{{$dealDic(contractTemplateType,row.tableRow,'label')}}</a-tag>
        </template>
        <!-- 指定品种 -->
        <template slot="category" slot-scope="category">
          <span>
            {{
              category.tableRow
                ? arrayToString(category.tableRow, "categoryName")
                : ""
            }}
          </span>
        </template>
        <!-- 指定公司 -->
        <template slot="company" slot-scope="company"  >
           <a-tooltip placement="topLeft">
              <template slot="title">
                <p  class="margin0" v-for="(item,index) in company.tableRow" :key="index">
                  {{item.companyName}}
                </p>
              </template>
           <span class="company">
            {{
              company.tableRow
                ? arrayToString(company.tableRow, "companyName")
                : ""
            }}
          </span>
            </a-tooltip>
         
        </template>
        <!-- 创建时间 -->
        <template slot="createDate" slot-scope="createDate">
          <span>
            {{ $getTime(createDate.tableRow) }}
          </span>
        </template>

        <!-- 表格操作按钮 -->
        <template slot="handle" slot-scope="row">
          <a @click="handleAdd(row.tableRow, 'edit')">
            <a-icon type="edit" />编辑
          </a>
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="onDel([row.tableRow.id])"
          >
            <p slot="title">是否确认要删除该合同模板？</p>
            <a-divider type="vertical" />
            <a type="link"> <a-icon type="delete" />删除 </a>
          </a-popconfirm>
        </template>
      </c-table>

      <!-- 新增/编辑弹窗 -->
      <a-modal
        :title="openType === 'edit' ? '编辑合同模板' : '新增合同模板'"
        :visible="dialogVisible"
        width="30%"
        @cancel="handleCancel"
        :confirm-loading="confirmLoading"
        :destroyOnClose="true"
      >
        <c-form-model
          checkStrictly
          :datas="formEditData"
          v-model="form"
          :rules="rules"
          ref="formModels"
        >
          <c-category
            v-if="this.form.templateLimit"
            slot="categoryIds"
            class="select-input"
            v-model="form.categoryIds"
            @change="onSearch"
            multiple
          ></c-category>
          <a-select
            @change="companySelectChange"
            v-if="this.form.templateLimit"
            slot="companyIds"
            showSearch
            mode="multiple"
            :option-filter-prop="'children'"
            :defaultValue="form.companyIds"
            placeholder="请选择或者搜索指定公司"
          >
            <a-select-option
              v-for="(item, idx) in allCompanysList"
              :key="idx"
              :value="item.value"
              >{{ item.label }}</a-select-option
            >
          </a-select>
          <!-- 模板类型 -->
          <a-radio-group slot="templateLimit" v-model="form.templateLimit">
            <a-radio
              @change="templateLimitSelect"
              v-for="(item, idx) in contractTemplateType"
              :value="item.value"
              :key="idx"
              >{{ item.label }}</a-radio
            >
          </a-radio-group>


            <a-button  class="display-inline download" slot="file" v-if="templateUrl"
            ><a-icon class="colorMain" type="download" /><a :href="templateUrl"
              >点击下载后预览</a
            ></a-button
          >
          <c-upload
            class="display-inline"
            slot="file"
            type="button"
            @change="uploadTemplateFile"
            accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            buttonName="立即上传"
          ></c-upload>
 
        </c-form-model>
        <div class="drawer-footer-btn flex-center">
          <a-space>
            <a-button @click="handleCancel">取消</a-button>
            <a-button type="primary" :loading="confirmLoading" @click="handleOk"
              >确定</a-button
            >
          </a-space>
        </div>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import {
  getContractTemplateList,
  uploadContractTemplate,
  getAllCompanys
} from "@/api/contractTemplate";
import { fileDownload } from "@/api/resource";
import { objFormData, arrayToString, getIds } from "@/util/common";
import { mapActions } from "vuex";
import { contractTemplateType } from "@/dict/contractTemplate";

export default {
  name: "AddressOfPre",
  components: {},
  data() {
    return {
      contractTemplateType,
      dialogVisible: false,
      templateUrl: "",
      confirmLoading: false,
      form: this.initializationParameter(),
      allCompanysList: [], //获取所有的公司列表
      tableSearchForm: {},
      tableSearchFormData: [
        {
          prop: "addBtn",
          type: "addBtn"
        }
      ],
      rules: {
        templateName: [
          { required: true, message: "请输入合同模板名称", trigger: "blur" }
        ],
        discountRowNum: [
          { required: true, message: "请输入合同折扣行数", trigger: "change" }
        ]
      },

      tableColumns: [
        {
          title: "序号",
          dataIndex: "id",
          align: "center",
          width: 120
        },
        {
          title: "合同模板名称",
          dataIndex: "templateName",
          align: "center"
        },
        {
          title: "模板类型",
          dataIndex: "templateLimit",
          align: "center",
          scopedSlots: { customRender: "templateLimit" }
        },
        {
          title: "模板指定品种",
          dataIndex: "category",
          align: "center",
          scopedSlots: { customRender: "category" }
        },
        {
          title: "模板指定公司",
          dataIndex: "company",
          align: "center",
          scopedSlots: { customRender: "company" },
          width: 200
        },
        {
          title: "合同折扣行数",
          dataIndex: "discountRowNum",
          align: "center"
        },
        {
          title: "合同税率",
          dataIndex: "taxRate",
          align: "center"
        },
        {
          title: "创建时间",
          dataIndex: "createDate",
          align: "center",
          scopedSlots: { customRender: "createDate" }
        },
        {
          title: "操作",
          key: "handle",
          scopedSlots: { customRender: "handle" },
          align: "center",
          width: 160
        }
      ],
      openType: "add",
      companyStatus: "",
      tableData: [],
      paginationDatas: {
        pageSizeOptions: [ "10", "20", "30", "40", "50", "200", "1000" ],
        pageSize: 10,
        pageNum: 1,
        total: 0
      }
    };
  },
  computed: {
    formEditData() {
      return [
        {
          label: "合同模板名称",
          prop: "templateName",
          maxLength: 20
        },
        {
          label: "合同限制",
          prop: "templateLimit",
          type: "slot"
        },

        {
          label: "合同折扣行数",
          prop: "discountRowNum"
        },
        {
          label: "合同税率",
          prop: "taxRate"
        },
        {
          label: "指定品种",
          prop: "categoryIds",
          hidden: this.form.templateLimit === false ? true : false,
          type: "slot"
        },
        {
          label: "指定公司",
          prop: "companyIds",
          hidden: this.form.templateLimit === false ? true : false,
          type: "slot"
        },

        {
          label: "合同模板文件",
          prop: "file",
          type: "slot"
        }
      ];
    }
  },
  created() {
    this.onPageOnlod();
    this.getAllCompany();
    this.getCategoryList();
  },
  mounted() {},
  methods: {
    ...mapActions([ "getCategoryList" ]),
    objFormData,
    arrayToString,
    onSearch(val) {
      // console.log(val)
    },
    companySelectChange(val) {
      this.form.companyIds = val;
    },
    templateLimitSelect() {
      if (this.form.templateLimit) {
        this.form.categoryIds = [];
        this.form.companyIds = [];
      }
    },
    //form初始化值
    initializationParameter() {
      return {
        templateName: undefined,
        templateType: 1,
        templateLimit: false,
        discountRowNum: undefined
      };
    },
    uploadTemplateFile(file) {
      this.form.file = file;
    },
    //初始化页面
    onPageOnlod() {
      this.loading = true;
      getContractTemplateList()
        .then(res => {
          this.tableData = res.data;
          this.paginationDatas.total = res.data.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    onShowNumChange(val) {
      this.paginationDatas.pageNum = val;
      this.onPageOnlod();
    },
    onPageSizeChange(val) {
      this.paginationDatas.pageSize = val;
      this.onPageOnlod();
    },

    //打开编辑、新增弹窗
    handleAdd(row, openType) {
      this.openType = openType;
      if (openType === "edit") {
        let editDatas = this.form;
        for (let key in editDatas) {
          editDatas[key] = row[key];
        }
        this.templateUrl = row.templateUrl ? row.templateUrl : "";
        this.form.templateType = 1;
        this.form.contractTemplateId = row.id;
        this.form.companyIds = getIds(row.company, "companyId");
        this.form.categoryIds = getIds(row.category, "categoryId");
      } else {
        this.form = this.initializationParameter();
        this.templateUrl =''
      }
      this.dialogVisible = true;
    },
    handleCancel() {
      this.dialogVisible = false;
    },
    //新增、编辑提交
    handleOk() {
      const that = this;
      this.dialogVisible = true;
      let onFun;
      let parmas = this.objFormData({
        ...this.form
      });
      this.$refs.formModels.handleValidate().then(data => {
        if (!this.form.file &&!this.templateUrl) {
          this.$message.error("合同模板文件");
          return;
        }
        that.confirmLoading = true;
        uploadContractTemplate(parmas)
          .then(res => {
            that.$message.success("操作成功");
            that.onPageOnlod();
            that.confirmLoading = false;
            this.dialogVisible = false;
            this.templateUrl =''
          })
          .catch(() => {
            this.confirmLoading = false;
          });
      });
    },

    //获取所有公司列表
    getAllCompany() {
      getAllCompanys()
        .then(res => {
          res = res.data;
          if (res.length > 0) {
            res.forEach(item => {
              (item.label = item.companyName), (item.value = item.id);
            });
            this.allCompanysList = res;
          }
        })
        .catch(() => {
          this.confirmLoading = false;
        });
    },
    onDel() {}
  }
};
</script>

<style lang="less" scoped>
@import '~@/style/index.less';
.contractTemplate-page{
  .testLink {
    border-color: #52c41a;
  }
  .company{
    display: block;
    text-align: center;
    .ellipsis(200px);
  }
}
.download{
    margin-right: 10px;
  }
</style>
